<template>
  <form>
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="onSubmit">
      <slot name="submit">
         <button class="btn btn-primariy">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
import mitt from 'mitt';

export const emitter = mitt()

type FormFuncProp = () => Boolean

export default defineComponent({
  emits: ['form-submit'],
  setup(props, context) {

    const funcArr: FormFuncProp[]  = []

    const onSubmit = () => {
      let result = funcArr.map(func => func()).every(v => v);
      context.emit('form-submit', result)
    }

    const callback:any = (func: FormFuncProp) => {
      funcArr.push(func)
    }

    emitter.on('item-created', callback)

    onUnmounted(() => {
      emitter.off('item-created', callback)
    })

    return {
      onSubmit
    }
  }
})
</script>
